﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace MopsesPetShop
{
    public partial class Default : Page
    {
        protected static string AddButtonText = "Добавить в корзину";
        protected static string DeleteButtonText = "Удалить из корзины";
        protected HyperLink payLink = new HyperLink
                                {
                                    Text = "Перейти к покупке",
                                    NavigateUrl = "Pay.aspx"
                                };
        protected HtmlGenericControl ClearText()
        {
            var ans = new HtmlGenericControl
                          {
                              InnerText = "Корзина пуста"
                          };

            return ans;
        }
        protected void RemoveDiv(Button button)
        {
            if (Request["basket"] != null)
                button.Parent.Parent.Parent.Controls.Remove(button.Parent.Parent);
            payLink.Visible = Session["Pets"] != null && ((List<Instances>)Session["Pets"]).Count > 0 ||
                              Session["Acc"] != null && ((List<AccInstances>)Session["Acc"]).Count > 0;
            if(!payLink.Visible)
                contentMainDiv.Controls.Add(ClearText());
        }

        protected void AddPetButton(object sender, EventArgs e)
        {
            var dc = new DataClasses1DataContext();
            var ekInstance = int.Parse(((HtmlGenericControl)((Button)sender).Controls[0]).InnerText);
            ((List<Instances>)Session["Pets"]).Add(dc.Instances.Where(pet => pet.pk == ekInstance).First());
            ((Button)sender).Text = DeleteButtonText;
            dc.Connection.Close();
        }

        protected void DeletePetButton(object sender, EventArgs e)
        {
            var ekInstance = int.Parse(((HtmlGenericControl)((Button)sender).Controls[0]).InnerText);
            ((List<Instances>)Session["Pets"]).RemoveAll(pet => pet.pk == ekInstance);
            ((Button)sender).Text = AddButtonText;
            RemoveDiv(sender as Button);
        }

        protected void AddAccButton(object sender, EventArgs e)
        {
            var dc = new DataClasses1DataContext();
            var ekInstance = int.Parse(((HtmlGenericControl)((Button)sender).Controls[0]).InnerText);
            ((List<AccInstances>)Session["Acc"]).Add(dc.AccInstances.Where(acc => acc.pk == ekInstance).First());
            ((Button)sender).Text = DeleteButtonText;
            dc.Connection.Close();
        }

        protected void DeleteAccButton(object sender, EventArgs e)
        {
            var ekInstance = int.Parse(((HtmlGenericControl)((Button)sender).Controls[0]).InnerText);
            ((List<Instances>)Session["Acc"]).RemoveAll(acc => acc.pk == ekInstance);
            ((Button)sender).Text = AddButtonText;
            RemoveDiv(sender as Button);
        }

        protected void CreateBox(DataClasses1DataContext dc, bool isAcc, int ekScope, int ekPreview, int ekEntity, int ekKind, int ekInstance = -1, bool showKind = false, bool kindLink = false)
        {
            var box = new HtmlGenericControl();
            box.Style.Add(HtmlTextWriterStyle.Display, "Block");
            box.Style.Add(HtmlTextWriterStyle.Position, "Relative");
            box.Style.Add(HtmlTextWriterStyle.MarginBottom, "50px");
            box.Style.Add("min-height", "150px");

            var img = new HtmlImage
            {
                Src = "ImageHandler.ashx?id=" + ekPreview + "&sizeW=400&sizeH=300",
                Alt = ""
            };
            img.Style.Add(HtmlTextWriterStyle.Height, "150px");
            img.Style.Add(HtmlTextWriterStyle.Margin, "20px");
            img.Style.Add(HtmlTextWriterStyle.MarginBottom, "0px");
            img.Style.Add(HtmlTextWriterStyle.Display, "Block");

            var leftField = new HtmlGenericControl();
            leftField.Style.Add(HtmlTextWriterStyle.Display, "Block");
            leftField.Controls.Add(img);
            leftField.Style.Add("float", "left");
            leftField.Style.Add(HtmlTextWriterStyle.Width, "200px");
            leftField.Style.Add(HtmlTextWriterStyle.MarginRight, "-250px");

            var center = new HtmlGenericControl();
            center.Style.Add(HtmlTextWriterStyle.Padding, "20px");

            HtmlGenericControl name;

            if (showKind && dc.Scopes.Where(sc => sc.pk == ekScope).First().scope == "Instances")
            {
                if (isAcc)
                    name = new HtmlGenericControl
                    {
                        InnerText = "Предмет: " + dc.AccKinds.Where(kind => kind.pk == ekKind).First().kind
                    };
                else
                {
                    name = new HtmlGenericControl
                               {
                                   InnerText =
                                       "Название класса: " + dc.Entities.Where(kind => kind.pk == ekEntity).First().entity
                               };
                    name.Style.Add(HtmlTextWriterStyle.Display, "block");
                    name.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
                    center.Controls.Add(name);
                    name = new HtmlGenericControl
                    {
                        InnerText = "Название вида: " + dc.Kinds.Where(kind => kind.pk == ekKind).First().kind
                    };
                }
                name.Style.Add(HtmlTextWriterStyle.Display, "block");
                name.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
                center.Controls.Add(name);
            }


            if (!isAcc)
                if (dc.Scopes.Where(sc => sc.pk == ekScope).First().scope == "Kinds")
                    name = new HtmlGenericControl
                               {
                                   InnerText = "Название вида: " + dc.Kinds.Where(kind => kind.pk == ekKind).First().kind
                               };
                else
                    name = new HtmlGenericControl
                               {
                                   InnerText = "Имя животного: " + dc.Instances.Where(ins => ins.pk == ekInstance).First().name
                               };
            else
            {
                if (dc.Scopes.Where(sc => sc.pk == ekScope).First().scope == "Kinds")
                    name = new HtmlGenericControl
                    {
                        InnerText = "Тип: " + dc.AccKinds.Where(kind => kind.pk == ekKind).First().kind
                    };
                else
                    name = new HtmlGenericControl
                    {
                        InnerText = "Название модели: " + dc.AccInstances.Where(ins => ins.pk == ekInstance).First().name
                    };
            }
            name.Style.Add(HtmlTextWriterStyle.Display, "block");
            name.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
            center.Controls.Add(name);


            if (dc.Scopes.Where(sc => sc.pk == ekScope).First().scope == "Instances")
            {
                name = new HtmlGenericControl
                {
                    InnerText =
                        "Цена: " +
                        (isAcc ?
                             dc.AccInstances.Where(ins => ins.pk == ekInstance).First().cost :
                             dc.Instances.Where(ins => ins.pk == ekInstance).First().cost)
                };
                name.Style.Add(HtmlTextWriterStyle.Display, "block");
                name.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
                center.Controls.Add(name);
            }

            if (!isAcc)
                foreach (var field in dc.Fields)
                {
                    if (field.ekScope != ekScope)
                        continue;
                    if (dc.Entities.Where(ent => ent.pk == field.ekEntity).First().pk != ekEntity)
                        continue;
                    var value =
                        dc.Valuess.Where(
                            val =>
                            val.ekField == field.pk && val.ekKindOrInstance == (ekInstance == -1 ? ekKind : ekInstance))
                            .FirstOrDefault();
                    if (value == null)
                        continue;
                    var currInfo = new HtmlGenericControl
                                                      {
                                                          InnerText = field.fieldName + ": " + value.value
                                                      };
                    currInfo.Style.Add(HtmlTextWriterStyle.Display, "block");
                    currInfo.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
                    center.Controls.Add(currInfo);
                }
            else
                if (dc.Scopes.Where(sc => sc.pk == ekScope).First().scope == "Instances")
                {

                    foreach (var field in dc.AccFields)
                    {
                        var value =
                            dc.AccValues.Where(
                                val =>
                                val.ekField == field.pk && val.ekInstance == (ekInstance == -1 ? ekKind : ekInstance))
                                .FirstOrDefault();
                        if (value == null)
                            continue;

                        var currInfo = new HtmlGenericControl
                                           {
                                               InnerText = field.fieldName + ": " + value.value
                                           };
                        currInfo.Style.Add(HtmlTextWriterStyle.Display, "block");
                        currInfo.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
                        center.Controls.Add(currInfo);
                    }
                }
            HyperLink hlink;
            if (dc.Scopes.Where(sc => sc.pk == ekScope).First().scope == "Kinds")
                if (!isAcc)
                    hlink = new HyperLink
                        {
                            NavigateUrl = "Default.aspx?entity=" + dc.Entities.Where(ent => ent.pk == ekEntity).First().entity + "&kind=" + dc.Kinds.Where(kind => kind.pk == ekKind).First().kind,
                            Text = "Показать перечень представителей вида"
                        };
                else
                    hlink = new HyperLink
                                {
                                    NavigateUrl =
                                        "Default.aspx?acc=true&kind=" +
                                        dc.AccKinds.Where(kind => kind.pk == ekKind).First().kind,
                                    Text = "Показать список товаров этой категории"
                                };
            else
            {
                hlink = new HyperLink
                            {
                                NavigateUrl =
                                    "Default.aspx?" + (isAcc ? "acc=true" : "entity=" + dc.Entities.Where(ent => ent.pk == ekEntity).First().entity) +
                                    "&kind=" + (isAcc ? dc.AccKinds.Where(kind => kind.pk == ekKind).First().kind : dc.Kinds.Where(kind => kind.pk == ekKind).First().kind) + "&instance=" +
                                    (isAcc ? dc.AccInstances.Where(ins => ins.pk == ekInstance).First().pk : dc.Instances.Where(ins => ins.pk == ekInstance).First().pk) + "&allPhotos=true",
                                Text = "Показать все фото"
                            };
                var divRight = new HtmlGenericControl();
                divRight.Style.Add("float", "Right");
                divRight.Style.Add(HtmlTextWriterStyle.Width, "200px");
                Button button;
                if (!isAcc)
                    if (((List<Instances>)Session["Pets"]).Exists(pet => pet.pk == ekInstance))
                    {
                        button = new Button
                        {
                            Text = DeleteButtonText
                        };
                        button.Click += DeletePetButton;
                    }
                    else
                    {
                        button = new Button
                                     {
                                         Text = AddButtonText
                                     };
                        button.Click += AddPetButton;
                    }
                else
                {
                    if (((List<AccInstances>)Session["Acc"]).Exists(acc => acc.pk == ekInstance))
                    {
                        button = new Button
                        {
                            Text = DeleteButtonText
                        };
                        button.Click += DeleteAccButton;
                    }
                    else
                    {
                        button = new Button
                        {
                            Text = AddButtonText
                        };
                        button.Click += AddAccButton;
                    }
                }
                button.Controls.Add(new HtmlGenericControl
                                        {
                                            InnerText = ekInstance.ToString(),
                                            Visible = false
                                        });
                button.Style.Add(HtmlTextWriterStyle.Width, "200px");
                divRight.Controls.Add(button);
                box.Controls.Add(divRight);
            }
            hlink.Style.Add(HtmlTextWriterStyle.MarginTop, "15px");
            hlink.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
            hlink.Style.Add(HtmlTextWriterStyle.Display, "Block");
            center.Controls.Add(hlink);
            if (dc.Scopes.Where(sc => sc.pk == ekScope).First().scope == "Instances" && !isAcc)
            {
                hlink = new HyperLink
                            {
                                NavigateUrl = "Default.aspx?recom=true&kind=" + dc.Kinds.Where(k => k.pk == ekKind).First().kind,
                                Text = "Показать рекомендуемые аксессуары"
                            };
                hlink.Style.Add(HtmlTextWriterStyle.MarginTop, "15px");
                hlink.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
                hlink.Style.Add(HtmlTextWriterStyle.Display, "Block");
                center.Controls.Add(hlink);
            }

            if (dc.Scopes.Where(sc => sc.pk == ekScope).First().scope == "Instances")
            {
                hlink = new HyperLink
                {
                    NavigateUrl = "Blog.aspx?" + (isAcc ? "acc=true" : "") + "kind=" + dc.Kinds.Where(k => k.pk == ekKind).First().kind + "&instance=" + ekInstance,
                    Text = "Перейти к обсуждению"
                };
                hlink.Style.Add(HtmlTextWriterStyle.MarginTop, "15px");
                hlink.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
                hlink.Style.Add(HtmlTextWriterStyle.Display, "Block");
                center.Controls.Add(hlink);
            }

            if (Request["recom"] != null && dc.Scopes.Where(sc => sc.pk == ekScope).First().scope == "Instances")
            {
                hlink = new HyperLink
                {
                    NavigateUrl = "Default.aspx?acc=true&kind=" + dc.AccKinds.Where(k => k.pk == ekKind).First().kind,
                    Text = "Выбрать другой аксессуар этого типа"
                };
                hlink.Style.Add(HtmlTextWriterStyle.MarginTop, "15px");
                hlink.Style.Add(HtmlTextWriterStyle.MarginLeft, "250px");
                hlink.Style.Add(HtmlTextWriterStyle.Display, "Block");
                center.Controls.Add(hlink);
            }

            box.Controls.Add(leftField);
            box.Controls.Add(center);

            contentMainDiv.Controls.Add(box);
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            miniTitle.InnerText = "Главная страница. Выберите класс интересующего вас животного";

            var dc = new DataClasses1DataContext();
            var requestEntity = Request["entity"];
            var requestKind = Request["kind"];
            var requestPhotos = Request["allPhotos"];
            if (Session["Pets"] == null)
                Session.Add("Pets", new List<Instances>());
            if (Session["Acc"] == null)
                Session.Add("Acc", new List<AccInstances>());




            if (Request["recom"] != null)
            {
                var kind = dc.Kinds.Where(k => k.kind.ToString() == requestKind).First();
                var entity = dc.Entities.Where(ent => ent.pk == kind.ekEntity).First();

                miniTitle.InnerText = "Рекомендуемые аксессуары для " + requestKind;


                foreach (var recomKind in dc.AccRecomKinds.Where(k => k.ekEntity == entity.pk))
                {
                    var recomInstance = dc.AccRecomInstance.Where(ins => ins.ekKind == recomKind.pk).FirstOrDefault();
                    if (recomInstance == null)
                    {
                        var scope = dc.Scopes.Where(sc => sc.scope == "Kinds").First().pk;
                        var preview = dc.AccKinds.Where(k => k.pk == recomKind.ekAccKind).First().ekPreview;
                        CreateBox(dc, true, scope, preview, -1, recomKind.pk);
                    }
                    else
                    {
                        var scope = dc.Scopes.Where(sc => sc.scope == "Instances").First().pk;
                        var preview = dc.AccInstances.Where(k => k.pk == recomInstance.ekAccInstance).First().ekPreview;
                        CreateBox(dc, true, scope, preview, -1, recomKind.pk, recomInstance.pk);
                    }
                }
                dc.Connection.Close();
                return;
            }

            if (Request["basket"] != null)
            {
                miniTitle.InnerText = "Содержимое корзины";
                contentMainDiv.Controls.Add(miniTitle);
                payLink.Style.Add(HtmlTextWriterStyle.Display, "block");
                contentMainDiv.Controls.Add(miniTitle);
                if (Session["Pets"] != null && ((List<Instances>)Session["Pets"]).Count > 0 || Session["Acc"] != null && ((List<AccInstances>)Session["Acc"]).Count > 0)
                    contentMainDiv.Controls.Add(payLink);
                else
                    contentMainDiv.Controls.Add(ClearText());
                foreach (var pet in ((List<Instances>)Session["Pets"]))
                {
                    var kind = dc.Kinds.Where(k => pet.ekKind == k.pk).First();
                    CreateBox(dc, false, dc.Scopes.Where(sc => sc.scope == "Instances").First().pk, pet.ekPreview, kind.ekEntity, pet.ekKind, pet.pk, true);
                }
                foreach (var acc in ((List<AccInstances>)Session["Acc"]))
                {
                    var kind = dc.Kinds.Where(k => acc.ekKind == k.pk).First();
                    CreateBox(dc, true, dc.Scopes.Where(sc => sc.scope == "Instances").First().pk, acc.ekPreview, kind.ekEntity, acc.ekKind, acc.pk, true);
                }
                dc.Connection.Close();
                return;
            }
            if (Request["acc"] != null)
            {
                if (string.IsNullOrEmpty(requestKind))
                    miniTitle.InnerText = "Перечень видов аксессуаров";
                else
                    miniTitle.InnerText = "Рекомендуемые аксессуары для " + requestKind;

                if (!string.IsNullOrEmpty(requestPhotos) && !string.IsNullOrEmpty(Request["instance"]))
                {
                    miniTitle.InnerText = "Все фото для " + requestKind + ": " + dc.AccInstances.Where(ins => ins.pk == int.Parse(Request["instance"])).First().name;

                    var pkInstance = int.Parse(Request["instance"]);
                    var file = "ImageHandler.ashx?id=" + dc.AccInstances.Where(ins => ins.pk == pkInstance).First().ekPreview + "&sizeW=400&sizeH=300";
                    var mi = new MenuItem("", "", file, "ImageHandler.ashx?id=" + dc.AccInstances.Where(ins => ins.pk == pkInstance).First().ekPreview);
                    myMenu.Items.Add(mi);
                    foreach (var picture in dc.Pictures)
                    {
                        if (!dc.AccMMI2P.ToList().Exists(mmi2p => mmi2p.ekInstance == pkInstance && mmi2p.ekPicture == picture.pk))
                            continue;
                        file = "ImageHandler.ashx?id=" + picture.pk + "&sizeW=400&sizeH=300";
                        mi = new MenuItem("", "", file, "ImageHandler.ashx?id=" + picture.pk);
                        myMenu.Items.Add(mi);
                    }
                    dc.Connection.Close();
                    return;
                }
                if (!string.IsNullOrEmpty(requestKind))
                {
                    miniTitle.InnerText = "Ассортимент: " + requestKind;

                    var pkKind = dc.AccKinds.Where(ent => ent.kind.ToString() == requestKind).First().pk;
                    foreach (var instance in dc.AccInstances.Where(ins => ins.ekKind == pkKind))
                        CreateBox(dc, true, dc.Scopes.Where(sc => sc.scope == "Instances").First().pk, instance.ekPreview, -1, pkKind, instance.pk);

                    dc.Connection.Close();
                    return;
                }

                foreach (var kind in dc.AccKinds)
                    CreateBox(dc, true, dc.Scopes.Where(sc => sc.scope == "Kinds").First().pk, kind.ekPreview, -1, kind.pk);

                dc.Connection.Close();
                return;
            }

            if (!string.IsNullOrEmpty(requestPhotos) && !string.IsNullOrEmpty(Request["instance"]))
            {
                miniTitle.InnerText = "Все фото для " + requestKind + ": " + dc.Instances.Where(ins => ins.pk == int.Parse(Request["instance"])).First().name;

                var pkInstance = int.Parse(Request["instance"]);
                var file = "ImageHandler.ashx?id=" + dc.Instances.Where(ins => ins.pk == pkInstance).First().ekPreview + "&sizeW=400&sizeH=300";
                var mi = new MenuItem("", "", file, "ImageHandler.ashx?id=" + dc.Instances.Where(ins => ins.pk == pkInstance).First().ekPreview);
                myMenu.Items.Add(mi);
                foreach (var picture in dc.Pictures)
                {
                    if (!dc.MMI2P.ToList().Exists(mmi2p => mmi2p.ekInstance == pkInstance && mmi2p.ekPicture == picture.pk))
                        continue;
                    file = "ImageHandler.ashx?id=" + picture.pk + "&sizeW=400&sizeH=300";
                    mi = new MenuItem("", "", file, "ImageHandler.ashx?id=" + picture.pk);
                    myMenu.Items.Add(mi);
                }
                dc.Connection.Close();
                return;
            }

            if (!string.IsNullOrEmpty(requestEntity) && !string.IsNullOrEmpty(requestKind))
            {
                miniTitle.InnerText = "Все животные вида: " + requestKind;

                var pkEntity = dc.Entities.Where(ent => ent.entity.ToString() == requestEntity).First().pk;
                var pkKind = dc.Kinds.Where(ent => ent.kind.ToString() == requestKind).First().pk;
                foreach (var instance in dc.Instances.Where(ins => ins.ekKind == pkKind))
                    CreateBox(dc, false, dc.Scopes.Where(sc => sc.scope == "Instances").First().pk, instance.ekPreview, pkEntity, pkKind, instance.pk);

                dc.Connection.Close();
                return;
            }

            if (!string.IsNullOrEmpty(requestEntity))
            {
                miniTitle.InnerText = "Все виды класса: " + requestEntity;
                contentMainDiv.Controls.Add(miniTitle);

                var pkEntity = dc.Entities.Where(ent => ent.entity.ToString() == requestEntity).First().pk;
                foreach (var kind in dc.Kinds.Where(kind => kind.ekEntity == pkEntity))
                    CreateBox(dc, false, dc.Scopes.Where(sc => sc.scope == "Kinds").First().pk, kind.ekPreview, kind.ekEntity, kind.pk);
                dc.Connection.Close();
                return;
            }
        }
    }
}